# Copyright 2006 Michael Gorsuch <michael@styledbits.com>

# This file is part of GrabTheMic <http://www.grabthemic.org>.

# GrabTheMic is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

require 'digest/sha1'

class User < ActiveRecord::Base
  
  attr_accessor :password
  
  has_many :stories
  has_many :votes
  has_many :comments
  
  validates_presence_of [:email, :password, :password_confirmation, :name]
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
  validates_length_of [:name], :minimum => 3, :too_short => "needs to be at least 3 characters long."
  validates_length_of [:password], :minimum => 6, :too_short => "needs to be at least 6 characters long."
  validates_confirmation_of :password
  validates_uniqueness_of [:email, :name]
  
  def before_save
    if !self.password.blank? 
      self.hashed_password = User.hash_password(self.password)
    end
    
    if User.count == 0
      self.admin = true
    end
    
  end
  
  def voted_for?(story)
    Vote.find(:first, :conditions => ["user_id=? and story_id=?",self.id, story.id])  
  end    
  
  def self.hash_password(clear_password)
    Digest::SHA1.hexdigest(clear_password)  
  end
  
  def self.login(email, password)
    User.find(:first, :conditions => ["email=? and hashed_password =?",email, User.hash_password(password)])
  end  
end